/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useEffect } from 'react';
import { Link, useIntl, connect } from 'umi';
import { createFromIconfontCN, SmileOutlined } from '@ant-design/icons';
import { Result, Button } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { getAuthorityFromRouter } from '@/utils/utils';
import logo from '../assets/logo.svg';
import { scriptUrl, RouterWithConfig } from "@/utils/config";
import arrayToTree from "array-to-tree";
import styles from "./BasicLayout.less"
const MyIcon = createFromIconfontCN({
  scriptUrl, // 在 iconfont.cn 上生成

});
import { TITLE } from "@/utils/config";

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);
/**
 * use Authorized check all menu item
 */

const menuDataRender = (menuList) => {
  return menuList.map((item) => {
    const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
    return Authorized.check(item.authority, localItem, null);
  });
  // // console.log(menuList);
  // const result = [
  //   ...menuList.map((item) => {
  //     const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
  //     console.log(Authorized.check(item.authority, localItem, null))
  //     return Authorized.check(item.authority, localItem, null);
  //   }),
  //   // {
  //   //   path: '/abgcdeg',
  //   //   name: '我是帅哥',
  //   //   icon: <MyIcon type="icon-editor" />
  //   //   // icon: React.createElement(require("@ant-design/icons").SmileOutlined, { style: { marginRight: "10px" } }),
  //   // },
  // ];
  // return result;
};

const getMenuList = (menuList) => {
  return menuList.map((item) => {
    const localItem = {
      ...item,
      icon: item.icon ? React.createElement(MyIcon, { style: { fontSize: "1em" }, type: item.icon }) : "",
      children: item.children ? getMenuList(item.children) : []
    };
    return localItem;
  });
};

const defaultFooterDom = (
  <DefaultFooter
    copyright={`2020 ${TITLE}`}
    links={[
      {
        key: 'jxzc',
        title: '技术支持 by：iver',
        // href: 'javascript:void(0)',
        blankTarget: true,
      },
      // {
      //   key: 'github',
      //   title: <GithubOutlined />,
      //   href: 'https://github.com/ant-design/ant-design-pro',
      //   blankTarget: true,
      // },
      // {
      //   key: 'Ant Design',
      //   title: 'Ant Design',
      //   href: 'https://ant.design',
      //   blankTarget: true,
      // },
    ]}
  />
);

const BasicLayout = (props) => {
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;
  /**
   * constructor
   */

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'sysUser/fetchCurrent',
      });
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = (payload) => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority

  const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
    authority: undefined,
  };
  // const {} = useIntl();
  return (
    <ProLayout
      logo={logo}
      className={styles.iverLayout}
      menuHeaderRender={(logoDom, titleDom) => (
        <Link to="/">
          {logoDom}
          {titleDom}
        </Link>
      )}
      onCollapse={handleMenuCollapse}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || menuItemProps.children || !menuItemProps.path) {
          return defaultDom;
        }
        return <Link target={menuItemProps.target} to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      breadcrumbRender={(routers = []) => {
        return [
          {
            path: '/',
            breadcrumbName: '首页',
          },
          ...routers,
        ]
      }}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
            <span>{route.breadcrumbName}</span>
          );
      }}
      footerRender={() => defaultFooterDom}
      menuDataRender={(menuList) => {
        if (RouterWithConfig) {
          return menuDataRender(menuList);
        }
        else {
          const { moduleList } = props.currentUser;
          if (moduleList == undefined) {
            return [];
          }
          const arr = moduleList.sort((a, b) => b.orderNum - a.orderNum).map(item => ({
            path: item.url ? item.url : "/",
            name: item.displayName,
            // target: "_blank",
            // icon: item.icon ? React.createElement(MyIcon, { style: { fontSize: 20 }, type: item.icon }) : "",
            icon: item.icon,
            fid: item.fid.toString(),
            id: item.id.toString(),
            target: item.moduleType === 1 ? "_blank" : "_self",
          }))

          const data = arrayToTree(arr, { rootID: "0", parentProperty: "fid", customID: "id", childrenProperty: "children" });
          return [{
            path: "/welcome",
            name: "欢迎",
            icon: <SmileOutlined />,
          }, ...getMenuList(data)];
        }
      }}
      rightContentRender={() => <RightContent />}
      {...props}
      {...settings}
    >
      <Authorized authority={authorized.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  );
};

export default connect(({ global, settings, sysUser }) => ({
  collapsed: global.collapsed,
  currentUser: sysUser.currentUser,
  settings,
}))(BasicLayout);
